package com.lzw.breezeNovel.webApp.service.impl.video;

import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.pojo.video.VideoCollect;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.mapper.video.VideoCollectMapper;
import com.lzw.breezeNovel.webApp.service.video.VideoCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.video
 * @date 2025/3/19
 * @description 视频收藏
 */

@Service
@SuppressWarnings("all")
public class VideoCollectServiceImpl implements VideoCollectService {

    /**
     * 注入视频收藏mapper
     */
    @Autowired
    private VideoCollectMapper videoCollectMapper;
    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 添加收藏
     * @param type
     * @param videoId
     */
    @Override
    public void addCollect(Integer type, Long videoId) {
        //获取当前用户id
        Long userId = getUserId();
        //创建视频收藏对象
        VideoCollect videoCollect = new VideoCollect();
        videoCollect.setUserId(userId);
        videoCollect.setVideoId(videoId);
        videoCollect.setType(type);
        videoCollectMapper.insert(videoCollect);

    }

    /**
     * 取消收藏
     * @param type
     * @param videoId
     */
    @Override
    public void cancelCollect(Integer type, Long videoId) {
        //获取当前用户id
        Long userId = getUserId();
        videoCollectMapper.cancelCollect(type,videoId,userId);
    }

    /**
     * 获取用户id
     */
    private Long getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        String phone = loginUser.getPhone();
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        return userInfo.getUserId();
    }

    /**
     * 判断是否收藏
     */
    @Override
    @Transactional(readOnly = true)
    public Boolean isCollect(Integer type, Long videoId) {
        //获取当前用户id
        Long userId = getUserId();
        return videoCollectMapper.isCollect(type,videoId,userId);
    }
}
